package com.xj.nrpc.consumer.client;

import com.alibaba.fastjson.JSONObject;
import com.xj.nrpc.consumer.handler.SimpleClientHandler;
import com.xj.nrpc.consumer.util.RequestEntity;
import com.xj.nrpc.consumer.util.ResponseEntity;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class TCPClient {

	public static final Bootstrap bootstrap = new Bootstrap();
	public static ChannelFuture f = null;
	static {

		EventLoopGroup group = new NioEventLoopGroup();
		bootstrap.group(group);
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
		bootstrap.handler(new ChannelInitializer<SocketChannel>() {
			protected void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()[0]));
				ch.pipeline().addLast(new StringDecoder());
				ch.pipeline().addLast(new SimpleClientHandler());
				ch.pipeline().addLast(new StringEncoder());
			};
		});

		try {
			f = bootstrap.connect("127.0.0.1", 8080).sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static ResponseEntity send(RequestEntity request) {
		f.channel().writeAndFlush(JSONObject.toJSONString(request));
		f.channel().writeAndFlush("\r\n");
		DefaultFuture df = new DefaultFuture(request);

		return df.get();
	}

}
